#! /bin/bash

if [ -n "$2" ] ;
then
  do_date=$2
else
  do_date=`date -d '-1 day' +%F`
fi

env_config="
use dw;
SET mapreduce.job.queuename=tianyan;
SET hive.exec.dynamic.partition.mode=nonstrict;
SET hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;"

dws_station_order_detail="
insert overwrite table dw.dws_station_order_detail partition (dt)
select
       order_id,
       collect_set(release_id)[0] as release_id,
       collect_set(rule_id)[0] as rule_id,
       collect_set(group_id)[0] as group_id,
       collect_set(company_id)[0] as company_id,
       collect_set(station_id)[0] as station_id,
       collect_set(p_cart_id)[0] as p_cart_id,
       collect_set(cart_id)[0] as cart_id,
       collect_set(c_discount_money)[0] as c_discount_money,
       collect_set(c_pay_money)[0] as c_pay_money,
       collect_set(mc_discount_money)[0] as mc_discount_money,
       collect_set(mc_pay_money)[0] as mc_pay_money,
       collect_set(total_money)[0] as total_money,
       collect_set(order_create_time)[0] as order_create_time,
       collect_set(fuel_no)[0] as fuel_no,
       collect_set(quantity)[0] as quantity,
       sum(related_amt) as related_amt,
       sum(if(rebate_type = 1, rebate_money, 0)) as rebate_money,
       sum(if(rebate_type = 2, rebate_money, 0)) as real_rebate_money,
       concat_ws(',', collect_set(rule_name)) as rule_name,
       concat_ws(',', collect_set(discount_type)) as discount_type,
       concat_ws(',', collect_set(discount_policy)) as discount_policy,
       collect_set(odt)[0] as dt
    from (
        select
               recharge_id,
               order_id,
               release_id,
               rule_id,
               dsrd.group_id,
               dsrd.company_id,
               station_id,
               p_cart_id,
               cart_id,
               c_discount_money,
               c_pay_money,
               mc_discount_money,
               mc_pay_money,
               total_money,
               order_create_time,
               fuel_no,
               quantity,
               related_amt,
               rebate_type,
               rebate_money,
               drr.rule_name,
               drr.discount_type,
               drr.discount_policy,
               dsrd.odt,
               rank() over (partition by odt, order_id, recharge_id, release_id, rule_id, rebate_type order by dsrd.create_time desc ) rank
        from dwd_station_rebate_detail dsrd
        left join dim_rebate_record drr on drr.id = dsrd.rule_id
        where dsrd.odt in (
            select partition_dt
            from dim_partition
            where business_type = 2 and dt = '$do_date')
             ) t1
    where rank = 1
    group by t1.order_id;"

insert_into_table(){
  case $1 in
  "all")
    echo $1
    hive -e "$env_config$dws_station_order_detail"
    ;;
  "dws_station_order_detail")
    echo $1
    hive -e "$env_config$dws_station_order_detail"
    ;;
  esac
}

insert_into_table $1